//
//  UIImage+Exs.swift
//  ttjx
//
//  Created by 文 on 2019/8/30.
//  Copyright © 2019 ttjx. All rights reserved.
//


import UIKit

extension UIImage {
    //MARK 更改图片颜色
    public func WHImageWithTintColor(color : UIColor) -> UIImage{
        let drawRect = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        
        color.setFill()
        UIRectFill(drawRect)
        draw(in: drawRect, blendMode: CGBlendMode.destinationIn, alpha: 1.0)
        let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return tintedImage!
    }
    
    // 更改为主颜色
    public func WHImageWithTintMainColor() -> UIImage {
        return WHImageWithTintColor(color: UIColor.THEME)
    }
    
    // 通过rect，裁切图片
    func WHImageCrop(toRect:CGRect) -> UIImage {
        
        let imageRef = self.cgImage?.cropping(to: toRect)
        let image = UIImage.init(cgImage: imageRef!, scale: self.scale, orientation: self.imageOrientation)
        
        return image
    }
    
    public func CTRenderingByMainColor() -> UIImage {
        let drawRect = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        
        UIColor.THEME.setFill()
        UIRectFill(drawRect)
        draw(in: drawRect, blendMode: CGBlendMode.destinationIn, alpha: 1.0)
        let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return tintedImage!
    }
}


//MARK -UIImage的处理
// 通过一个控件生成一张图片
func WHImage_createdWithView(view : UIView) -> UIImage {
    
    let size = view.bounds.size
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.main.scale)
    view.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}

public func createImageWithColor(color:UIColor) -> UIImage {
    let rect = CGRect.init(x:0, y:0, width:1.0, height:1.0)

    UIGraphicsBeginImageContext(rect.size)

    let context = UIGraphicsGetCurrentContext()

    context!.setFillColor(color.cgColor)

    context!.fill(rect)

    let image = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return image!
}
